# coding:utf-8

import socket
import errno
import threading
import time

EOL1 = b'\n\n'
EOL2 = b'\n\r\n'
body = 'hello, world<h1> from tjh </h1>-from {thread_name}'
resp_params = [
    'HTTP/1.0 200 OK',
    'Date: Sun, 31 jul 2024 09:35:33 GMT',
    'Content-Type: text/html; charset=utf-8',
    'Content-Length: {length}\r\n',
    body
]

resp = '\r\n'.join(resp_params)

def handle_connection(conn, addr):
    req = b''
    while EOL1 not in req and EOL2 not in req:
        req += conn.recv(1024)
    print(req)
    current_thread = threading.currentThread()
    content_length = len(body.format(thread_name=current_thread.name).encode())
    print(current_thread.name)
    conn.send(resp.format(thread_name=current_thread.name, length=content_length).encode())
    conn.close()
    
def main():
    ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # ss.setblocking(0)  # set socket mode as non block 
    # ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    ss.bind(('127.0.0.1', 8000))
    ss.listen(10)  # conn max queue number
    print('http://127.0.0.1:8000')
    # ss.setblocking(0)  # set socket mode as non block 
    
    try:
        i = 0
        while True:
            try:
                conn, addr = ss.accept()
            except socket.error as e:
                if e.args[0] != errno.EAGAIN:
                    raise
                continue
            i += 1
            print(i)
            t = threading.Thread(target=handle_connection, args=(conn, addr), name='thread-%s' % i)
            t.start()
    finally:
        ss.close()
        
if __name__ == '__main__':
    main()